<template>
  <div class="job-search-container">
    <!-- 搜索栏 -->
    <div class="search-header">
      <!--      <h2 class="search-title">职位类型</h2>-->
      <!--      <div class="search-bar">-->
      <!--        <input type="text" v-model="searchKeyword" placeholder="搜索职位、公司" class="search-input"/>-->
      <!--        <button class="search-button" @click="handleSearch">搜索</button>-->
      <!--      </div>-->
      <SearchBar @search="handleSearch"/>
    </div>

    <!-- 筛选条件栏 -->
    <div class="filter-container">
      <!-- 公司地点筛选 -->
      <div class="filter-section">
        <span class="filter-label">公司地点：</span>
        <div class="filter-options">
          <span
              class="filter-option"
              :class="{active: selectedCity === '0'}"
              @click="selectCity('0')"
          >
            全国
          </span>
          <span
              v-for="city in displayedCities"
              :key="city.id"
              class="filter-option"
              :class="{active: selectedCity === city.id}"
              @click="selectCity(city.id)"
          >
            {{ city.name }}
          </span>
          <span
              class="filter-option more-cities"
              @click="showAllCities = true"
          >
            全部城市
          </span>
        </div>
      </div>

      <!-- 行业类型筛选 -->
      <div class="filter-section">
        <span class="filter-label">行业类型：</span>
        <div class="filter-options">
          <span
              class="filter-option"
              :class="{active: selectedIndustry === '0'}"
              @click="selectIndustry('0')"
          >
            不限
          </span>
          <span
              v-for="industry in industryList"
              :key="industry.id"
              class="filter-option"
              :class="{active: selectedIndustry === industry.id}"
              @click="selectIndustry(industry.id)"
          >
            {{ industry.name }}
          </span>
        </div>
      </div>

      <!-- 融资阶段筛选 -->
      <div class="filter-section">
        <span class="filter-label">融资阶段：</span>
        <div class="filter-options">
          <span
              class="filter-option"
              :class="{active: selectedFinance === ''}"
              @click="selectFinance('')"
          >
            不限
          </span>
          <span
              class="filter-option"
              :class="{active: selectedFinance === '0'}"
              @click="selectFinance('0')"
          >
            未融资
          </span>
          <span
              class="filter-option"
              :class="{active: selectedFinance === '1'}"
              @click="selectFinance('1')"
          >
            天使轮
          </span>
          <span
              class="filter-option"
              :class="{active: selectedFinance === '2'}"
              @click="selectFinance('2')"
          >
            A轮
          </span>
          <span
              class="filter-option"
              :class="{active: selectedFinance === '3'}"
              @click="selectFinance('3')"
          >
            B轮
          </span>
          <span
              class="filter-option"
              :class="{active: selectedFinance === '4'}"
              @click="selectFinance('4')"
          >
            C轮
          </span>
          <span
              class="filter-option"
              :class="{active: selectedFinance === '5'}"
              @click="selectFinance('5')"
          >
            D轮及以上
          </span>
          <span
              class="filter-option"
              :class="{active: selectedFinance === '6'}"
              @click="selectFinance('6')"
          >
            已上市
          </span>
          <span
              class="filter-option"
              :class="{active: selectedFinance === '7'}"
              @click="selectFinance('7')"
          >
            不需要融资
          </span>
        </div>
      </div>

      <!-- 公司规模筛选 -->
      <div class="filter-section">
        <span class="filter-label">公司规模：</span>
        <div class="filter-options">
          <span
              class="filter-option"
              :class="{active: selectedCompanyScale === '0'}"
              @click="selectCompanyScale('0')"
          >
            不限
          </span>
          <span
              class="filter-option"
              :class="{active: selectedCompanyScale === '1'}"
              @click="selectCompanyScale('1')"
          >
            0-20人
          </span>
          <span
              class="filter-option"
              :class="{active: selectedCompanyScale === '2'}"
              @click="selectCompanyScale('2')"
          >
            20-99人
          </span>
          <span
              class="filter-option"
              :class="{active: selectedCompanyScale === '3'}"
              @click="selectCompanyScale('3')"
          >
            100-499人
          </span>
          <span
              class="filter-option"
              :class="{active: selectedCompanyScale === '4'}"
              @click="selectCompanyScale('4')"
          >
            500-999人
          </span>
          <span
              class="filter-option"
              :class="{active: selectedCompanyScale === '5'}"
              @click="selectCompanyScale('5')"
          >
            1000-9999人
          </span>
          <span
              class="filter-option"
              :class="{active: selectedCompanyScale === '6'}"
              @click="selectCompanyScale('6')"
          >
            10000人以上
          </span>
        </div>
      </div>

      <button class="clear-filters" @click="clearFilters">清空筛选条件</button>
    </div>

    <!-- 默认推荐标题 -->
    <div class="recommend-title">
      <span>默认推荐</span>
      <span class="sub-title">根据求职期望推荐</span>
    </div>

    <!-- 公司列表 -->
    <div class="company-list">
      <div class="company-card" v-for="company in companyList" :key="company.id">
        <div class="card-header" @click="goCompanyDetail(company.id)">
          <img :src="company.logo" alt="公司logo" class="company-logo"/>
          <div class="company-info">
            <h3 class="company-name">{{ company.name }}</h3>
            <div class="company-meta">
              <span class="meta-label">地点：</span>
              <span>{{ company.location || '未标注' }}</span>
            </div>
          </div>
        </div>
        <div class="card-body">
          <div class="company-tags">
            <span v-if="company.is_listed !== null" class="tag">
              <template v-if="company.is_listed === 0">未融资</template>
              <template v-else-if="company.is_listed === 1">天使轮</template>
              <template v-else-if="company.is_listed === 2">A轮</template>
              <template v-else-if="company.is_listed === 3">B轮</template>
              <template v-else-if="company.is_listed === 4">C轮</template>
              <template v-else-if="company.is_listed === 5">D轮及以上</template>
              <template v-else-if="company.is_listed === 6">已上市</template>
              <template v-else-if="company.is_listed === 7">不需要融资</template>
            </span>
            <span v-if="company.description" class="tag desc-tag">{{ company.description }}</span>
          </div>
        </div>

      </div>
    </div>

    <!-- 全部城市弹窗 -->
    <div class="city-modal" v-if="showAllCities">
      <div class="modal-content">
        <div class="modal-header">
          <h3>请选择城市</h3>
          <span class="close-btn" @click="showAllCities = false">&times;</span>
        </div>
        <div class="modal-body">
          <!-- 热门城市 -->
          <div class="city-group">
            <h4 class="group-title">热门城市</h4>
            <div class="city-list">
              <span
                  v-for="city in hotCities"
                  :key="city.id"
                  class="city-item"
                  :class="{active: selectedCity === city.id}"
                  @click="selectCityInModal(city.id)"
              >
                {{ city.name }}
              </span>
            </div>
          </div>

          <!-- 按字母分类的城市 -->
          <div
              v-for="(group, letter) in groupedCities"
              :key="letter"
              class="city-group"
          >
            <h4 class="group-title">{{ letter }}</h4>
            <div class="city-list">
              <span
                  v-for="city in group"
                  :key="city.id"
                  class="city-item"
                  :class="{active: selectedCity === city.id}"
                  @click="selectCityInModal(city.id)"
              >
                {{ city.name }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, computed, onMounted} from 'vue';
import axios from 'axios';
import SearchBar from '../components/SearchBar.vue'
import {useRouter} from "vue-router";

let router = useRouter();

// 响应式数据
const searchKeyword = ref('');
const selectedCity = ref('0');
const selectedIndustry = ref('0');
const selectedFinance = ref('');
const selectedCompanyScale = ref('0');
const cityList = ref([]);
const industryList = ref([]);
const companyList = ref([]);
const num1 = ref(0);
const num2 = ref(0);
const showAllCities = ref(false);


// 热门城市名称列表 - 根据图片调整
const hotCityNames = ['北京市', '天津市', '上海市', '重庆市', '石家庄市', '黑山市', '秦皇岛市', '太原市', '大同市', '晋中市'];

// 页面加载时获取城市列表和行业列表
onMounted(() => {
  getCityList();
  getIndustryList();
  getCompanyList();
});

// 计算属性
const displayedCities = computed(() => {
  return hotCities.value.slice(0, 10);
});

const hotCities = computed(() => {
  return cityList.value.filter(city => hotCityNames.includes(city.name));
});

const groupedCities = computed(() => {
  const groups = {};

  cityList.value.forEach(city => {
    if (hotCityNames.includes(city.name)) return;

    const firstLetter = getFirstLetter(city.name);
    if (!groups[firstLetter]) {
      groups[firstLetter] = [];
    }
    groups[firstLetter].push(city);
  });

  return Object.keys(groups).sort().reduce((acc, key) => {
    acc[key] = groups[key];
    return acc;
  }, {});
});

// 获取城市列表
const getCityList = () => {
  axios.get('http://127.0.0.1:8000/home/citylist/')
      .then((res) => {
        if (res.data.code === 200) {
          cityList.value = res.data.data;
        }
      })
      .catch((err) => {
        console.error('获取城市列表失败：', err);
      });
};

// 获取行业列表
const getIndustryList = () => {
  axios.get('http://127.0.0.1:8000/home/jobCategories/')
      .then((res) => {
        if (res.data.code === 200) {
          industryList.value = res.data.data;
        }
      })
      .catch((err) => {
        console.error('获取行业列表失败：', err);
      });
};

const getCompanyScale = () => {
  if (selectedCompanyScale.value === '0') {
    num1.value = 0;
    num2.value = 0;
  } else if (selectedCompanyScale.value === '1') {
    num1.value = 0;
    num2.value = 20;
  } else if (selectedCompanyScale.value === '2') {
    num1.value = 21;
    num2.value = 99;
  } else if (selectedCompanyScale.value === '3') {
    num1.value = 100;
    num2.value = 499;
  } else if (selectedCompanyScale.value === '4') {
    num1.value = 500;
    num2.value = 999;
  } else if (selectedCompanyScale.value === '5') {
    num1.value = 1000;
    num2.value = 9999;
  } else if (selectedCompanyScale.value === '6') {
    num1.value = 10000;
    num2.value = '';
  }
};

// 获取公司列表
const getCompanyList = (params = {}) => {
  const queryParams = {
    city: selectedCity.value === '0' ? '' : selectedCity.value,
    job: selectedIndustry.value === '0' ? '' : selectedIndustry.value,
    finance: selectedFinance.value,
    num1: num1.value,
    num2: num2.value,
  };
  Object.assign(queryParams, params);
  axios.get('http://127.0.0.1:8000/home/companyList/', {params: queryParams})
      .then((res) => {
        if (res.data.code === 200) {
          companyList.value = res.data.data;
        }
      })
      .catch((err) => {
        console.error('获取公司列表失败：', err);
      });
};

// 筛选条件改变时重新获取公司列表
const handleFilterChange = () => {
  getCompanyScale();
  getCompanyList();
};

// 搜索按钮点击事件
const handleSearch = () => {
  getCompanyList({keyword: searchKeyword.value});
};

// 获取公司规模文本
const getCompanyScaleText = (company) => {
  const scaleMap = {
    0: '规模未标注',
    1: '0-20人',
    2: '20-99人',
    3: '100-499人',
    4: '500-999人',
    5: '1000-9999人',
    6: '10000人以上',
  };
  return scaleMap[company.scale] || '规模未标注';
};

// 辅助函数：获取拼音首字母
const getFirstLetter = (str) => {
  if (!str) return '#';
  const firstChar = str.charAt(0);
  if (/[a-zA-Z]/.test(firstChar)) {
    return firstChar.toUpperCase();
  }
  if (/[0-9]/.test(firstChar)) {
    return '#';
  }
  return firstChar;
};

const goCompanyDetail = (id) => {
  router.push(`/companyDetail/?id=${id}`);
}

// 在弹窗中选择城市
const selectCityInModal = (id) => {
  selectedCity.value = id;
  showAllCities.value = false;
  handleFilterChange();
};

// 选择城市
const selectCity = (id) => {
  selectedCity.value = id;
  handleFilterChange();
};

const selectIndustry = (id) => {
  selectedIndustry.value = id;
  handleFilterChange();
};

const selectFinance = (id) => {
  selectedFinance.value = id;
  handleFilterChange();
};

const selectCompanyScale = (id) => {
  selectedCompanyScale.value = id;
  handleFilterChange();
};

const clearFilters = () => {
  selectedCity.value = '0';
  selectedIndustry.value = '0';
  selectedFinance.value = '';
  selectedCompanyScale.value = '0';
  searchKeyword.value = '';
  handleFilterChange();
};
</script>

<style scoped>
/* 基础样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.job-search-container {
  width: 90%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px 0;
}

/* 搜索标题和搜索栏 */
.search-header {
  margin-bottom: 25px;
}

.search-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 15px;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-input {
  flex: 1;
  padding: 12px 15px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 14px;
  outline: none;
  transition: all 0.3s;
}

.search-input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.search-button {
  padding: 12px 25px;
  background-color: #fff;
  color: #1890ff;
  border: 1px solid #1890ff;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.search-button:hover {
  background-color: #1890ff;
  color: #fff;
}

/* 筛选条件栏 */
.filter-container {
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.filter-section {
  margin-bottom: 15px;
}

.filter-label {
  display: inline-block;
  font-size: 14px;
  color: #666;
  white-space: nowrap;
  margin-right: 8px;
  vertical-align: top;
  line-height: 32px;
}

.filter-options {
  display: inline-flex;
  flex-wrap: wrap;
  gap: 8px;
}

.filter-option {
  display: inline-block;
  padding: 5px 12px;
  font-size: 13px;
  color: #666;
  border-radius: 3px;
  cursor: pointer;
  transition: all 0.2s;
  background-color: #fff;
  border: 1px solid #e8e8e8;
}

.filter-option:hover {
  color: #1890ff;
  border-color: #1890ff;
}

.filter-option.active {
  color: #1890ff;
  background-color: #fff;
  border-color: #1890ff;
}

/* 全部城市按钮样式 */
.more-cities {
  color: #666;
  background-color: #fff;
  border: 1px solid #e8e8e8;
}

.more-cities:hover {
  color: #1890ff;
  border-color: #1890ff;
  background-color: #fff;
}

.clear-filters {
  margin-top: 10px;
  padding: 5px 10px;
  background: #fff;
  border: 1px solid #e8e8e8;
  color: #666;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s;
  border-radius: 3px;
}

.clear-filters:hover {
  color: #1890ff;
  border-color: #1890ff;
}

/* 推荐标题 */
.recommend-title {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.recommend-title .sub-title {
  margin-left: 15px;
  font-size: 13px;
  font-weight: normal;
  color: #999;
}

/* 公司列表样式 */
.company-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 25px;
}

.company-card {
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
  border: 1px solid #ebeef5;
}

.company-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.company-logo {
  width: 70px;
  height: 70px;
  object-fit: cover;
  border-radius: 6px;
}

.company-info {
  margin-left: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.company-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.company-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  font-size: 13px;
  color: #909399;
}

.meta-label {
  color: #c0c4cc;
}

.card-body {
  padding: 15px 20px 20px;
}

.company-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 15px;
}

.tag {
  display: inline-block;
  padding: 4px 12px;
  background-color: #f5f7fa;
  color: #606266;
  border-radius: 20px;
  font-size: 12px;
  white-space: nowrap;
}

.desc-tag {
  background-color: #ecf5ff;
  color: #409EFF;
}

.card-footer {
  padding: 15px 20px;
  background-color: #f5f7fa;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 13px;
  color: #606266;
}

.company-scale {
  display: flex;
  align-items: center;
}

.company-scale::before {
  content: '';
  display: inline-block;
  width: 14px;
  height: 14px;
  margin-right: 5px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 24 24' fill='none' stroke='%23909399' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2'%3E%3C/path%3E%3Ccircle cx='9' cy='7' r='4'%3E%3C/circle%3E%3Cline x1='21' y1='12' x2='9' y2='12'%3E%3C/line%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-size: contain;
}

/* 城市弹窗样式 */
.city-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  border-radius: 8px;
  width: 80%;
  max-width: 800px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.close-btn {
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #333;
}

.modal-body {
  padding: 16px 24px;
}

.city-group {
  margin-bottom: 20px;
}

.group-title {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #666;
  font-weight: 500;
}

.city-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.city-item {
  padding: 6px 12px;
  background-color: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.city-item:hover {
  background-color: #fff;
  color: #1890ff;
  border-color: #1890ff;
}

.city-item.active {
  background-color: #fff;
  color: #1890ff;
  border: 1px solid #1890ff;
}
</style>